#include <Arduino.h>
#include <PubSubClient.h>
#include "espUtils.h"
IPAddress server(183,230,40,39);        // OneNet的服务器地址
WiFiClient wifiClient;               // 声明一个WiFiClient对象，用来初始化 MQTT对象

void callback(char *topic, byte *payload, unsigned int length);
PubSubClient MQTTClient(server, 6002, callback, wifiClient);                // 声明一个MQTT对象


/* OneNet自己定义设备的信息 */
#define PRODUCT_ID "364314"
#define API_KEY "o4qzEqGG0nmMmS2EjLnjI=7sizM="
#define DEVICE_ID "615012994"
#define TOPIC "esp8266led"
const char ssid[] = "CU_bRbv";
const char pass[] = "xrfgwxtm";
void setup()
{

    Serial.begin(115200);
    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, pass);           // WIFI1信息
    Serial.println("");
    Serial.print("connect wifi is ");
    Serial.println(WiFi.SSID());
    while(WiFi.status() != WL_CONNECTED){
        Serial.print(".");
        delay(500);
    }
    Serial.println("");
    Serial.print(WiFi.SSID());
    Serial.println("is connected.");


    
    // MQTTClient.setServer(server, 6002);        // 设置服务器信息
    // MQTTClient.setClient(wifiClient);          // 设置连接的Client实例
    // MQTTClient.setCallback(callback);          // 设置MQTT对象的回掉函数

    pinMode(16, OUTPUT);
    pinMode(2, OUTPUT);                          // 将NodeMCU的LED灯设置成output状态, 因为该百年其电压来点亮与熄灭
    delay(1500);
}

void loop()
{
    if (!MQTTClient.connected()) {
        reconnect(PRODUCT_ID, API_KEY, DEVICE_ID);
    }
    MQTTClient.loop();
}

// 回调函数，用来打印出信息的主题、返回信息和长度
void callback(char* topic, byte* payload, unsigned int length) {
    Serial.print("Message arrived [");
    Serial.print(topic);
    Serial.print("] ");
    for (int i=0; i<length; i++) {
        Serial.print((char)payload[i]);
    }
    Serial.println();

    if ((char)payload[0] == '1') {
        digitalWrite(2, LOW);
        digitalWrite(16, HIGH);
    } else {
        digitalWrite(2, HIGH);
        digitalWrite(16, LOW);
    }
}

// 重连接
void reconnect(char *onenet_productId, char *onenet_apiKey, char *onenet_deviceId) {
    
    while (!MQTTClient.connected()) {
        Serial.print("Attempting MQTT connection...");
        // Attempt to connect
        if (MQTTClient.connect(onenet_deviceId,onenet_productId,onenet_apiKey)) {
            Serial.println("connected");
            // Once connected, publish an announcement...
            MQTTClient.publish("outTopic","hello world");
            // ... and resubscribe
            MQTTClient.subscribe(TOPIC, 1);
        } else {
            Serial.print("failed, rc=");
            Serial.print(MQTTClient.state());
            Serial.println(" try again in 5 seconds");
            // Wait 5 seconds before retrying
            delay(5000);
        }
    }
}
